package com.wt.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wt.admin.config.SecUtils;
import com.wt.admin.entity.*;
import com.wt.admin.entity.rewentity.LoginUser;
import com.wt.admin.packClass.Article;
import com.wt.admin.service.WqunAdminService;
import com.wt.admin.service.WqunSysRoleMenuService;
import com.wt.admin.service.WqunSysRoleService;
import com.wt.admin.service.impl.UserDetailsServiceImpl;
import com.wt.commonutils.R;
import com.wt.oos.Upload;
import com.wt.redis.RedisCache;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author wt
 * @since 2023-10-10
 */
@RestController
@RequestMapping("/wqunSysRole")
public class WqunSysRoleController {

    @Autowired
    private WqunSysRoleService wqunSysRoleService;

    @Autowired
    private WqunSysRoleMenuService wqunSysRoleMenuService;

    @Autowired
    private WqunAdminService wqunAdminService;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private RedisCache redisCache;

    @ApiOperation("管理员查看某角色的权限")
    @GetMapping("/getRoleById/{roleId}")
    @PreAuthorize("hasAnyAuthority('admin:wqunSysRole:getRoleById')")
    public R getRoleById(@PathVariable("roleId") Long roleId){
        WqunSysRole getRoleById = wqunSysRoleService.getById(roleId);
        return getRoleById != null?R.ok().data("getRoleById",getRoleById):R.error().message("查找失败");
    }

    @ApiOperation("超级管理员修改某角色的描述信息")
    @PostMapping("/updateRole")
    @PreAuthorize("hasAnyAuthority('super:wqunSysRole:updateRole')")
    public R updateRole(@RequestBody WqunSysRole wqunSysRole){
        boolean getRoleById = wqunSysRoleService.updateById(wqunSysRole);
        return getRoleById?R.ok().message("修改成功"):R.error().message("修改失败");
    }

    @ApiOperation("超级管理员修改某角色的描述信息")
    @PostMapping("/deleteRole")
    @PreAuthorize("hasAnyAuthority('super:wqunSysRole:deleteRole')")
    public R deleteRole(@RequestBody WqunSysRole wqunSysRole){
        wqunSysRole.setIsDelete("1");
        wqunSysRole.setStatus("1");
        boolean getRoleById = wqunSysRoleService.updateById(wqunSysRole);
        return getRoleById?R.ok().message("删除成功"):R.error().message("删除失败");
    }

    @ApiOperation("超级用户添加角色")
    @PostMapping("/addRole")
    @PreAuthorize("hasAnyAuthority('super:wqunSysRole:addRole')")
    public R addRole(@RequestBody WqunSysRole wqunSysRole){
        QueryWrapper<WqunSysRole> wqunSysRoleQueryWrapper = new QueryWrapper<>();
        wqunSysRoleQueryWrapper.orderByDesc("id");
        WqunSysRole one = wqunSysRoleService.getOne(wqunSysRoleQueryWrapper);
        String userId = SecUtils.getUserMess().getId();
        wqunSysRole.setId(one.getId() + 1);
        wqunSysRole.setCreateBy(userId);
        wqunSysRole.setUpdateBy(userId);
        boolean save = wqunSysRoleService.save(wqunSysRole);
        return save?R.ok().message("添加成功"):R.error().message("添加失败");
    }

    @ApiOperation("管理员查询角色")
    @GetMapping("/findAllRole")
    @PreAuthorize("hasAnyAuthority('admin:wqunSysRole:findAllRole')")
    public R findAllRole(){
        QueryWrapper<WqunSysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete","0");
        List<WqunSysRole> findAllRole = wqunSysRoleService.list(queryWrapper);
        return findAllRole.size() == 0?R.error().message("查询失败"):R.ok().data("findAllRole",findAllRole);
    }

    @ApiOperation("管理员修改角色权限")
    @RequestMapping("/updateRoleMenu/{roleId}")
    @PreAuthorize("hasAnyAuthority('admin:wqunSysRole:updateRoleMenu')")
    public R updateRoleMenu(@RequestBody String[] updateRoleMenuIdList,@PathVariable("roleId") String roleId){
        QueryWrapper<WqunSysRoleMenu> wqunSysRoleMenuQueryWrapper = new QueryWrapper<>();
        wqunSysRoleMenuQueryWrapper.eq("role_id",roleId);
        wqunSysRoleMenuService.remove(wqunSysRoleMenuQueryWrapper);
        WqunSysRoleMenu wqunSysRoleMenu = new WqunSysRoleMenu();
        String userId = SecUtils.getUserMess().getId();
        for (String s : updateRoleMenuIdList) {
            wqunSysRoleMenu.setRoleId(Long.valueOf(roleId));
            wqunSysRoleMenu.setMenuId(Long.valueOf(s));
            wqunSysRoleMenu.setCreateBy(Long.valueOf(userId));
            wqunSysRoleMenu.setUpdateBy(Long.valueOf(userId));
            boolean b = wqunSysRoleMenuService.save(wqunSysRoleMenu);
            if(!b) return R.error().message("修改出现错误");
        }

        //修改redis中缓存的用户权限
        QueryWrapper<WqunAccount> wqunAccountQueryWrapper = new QueryWrapper<>();
        wqunAccountQueryWrapper.eq("user_type",roleId);
        List<WqunAccount> wqunAccountList = wqunAdminService.list(wqunAccountQueryWrapper);
        for (WqunAccount wqunAccount : wqunAccountList) {
            String redisKey = "login:" + wqunAccount.getId();
            LoginUser cacheObject = redisCache.getCacheObject(redisKey);
            if(cacheObject != null){
                UserDetails userDetails = userDetailsService.loadUserByUsername(wqunAccount.getPhone());
                redisCache.setCacheObject(redisKey,userDetails);
            }
        }


        return R.ok().message("修改成功");
    }

    @ApiOperation("管理员管理角色")
    @GetMapping("/bitRole/{id}")
    @PreAuthorize("hasAnyAuthority('admin:wqunSysRole:bitRole')")
    public R bitRole(@PathVariable("id") String id){
        WqunSysRole byId = wqunSysRoleService.getById(id);
        byId.setStatus(byId.getStatus().equals("0")?"1":"0");
        boolean b = wqunSysRoleService.updateById(byId);
        return b?R.ok().message("修改成功"):R.error().message("修改失败");
    }
}

